﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web.Mvc;

using ProjectBase.Core;
using ProjectBase.Core.Service;
using ProjectBase.Core.Web;
using ProjectBase.Mvc;
using ProjectBase.Mvc.Web;

using $prjsn$.Common;

namespace $safeprojectname$
{
    /// <summary>
    ///     Stores Exception in the controller.model.Messages collection
    ///     and redirects to Error screen (instead of breakdown).
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class ExceptionHandlerAttribute : ExceptionBaseAttribute
    {
        const string View = "Error";

        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception is DaoException
                || filterContext.Exception.InnerException is DaoException)
            {
                base.DisposeApplicationObjects();
                Factory.CreateInstance<IResetCacheFacade>().ResetStaticCaches(filterContext);
                filterContext.Session().Clear(); // damaged Filter criteria should be cleaned
                PublishingManager.Publish(filterContext.Controller, null, filterContext.Exception);
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Redirect(Str.WebControls.NotAvailable);
                return;
            }
            var controllerName = (string)filterContext.RouteData.Values[Str.Common.Controller];
            var action = (string)filterContext.RouteData.Values[Str.Common.Action];
            var controller = filterContext.Controller as ICoreController<ICoreModel>;

            controller.PublishFatal(filterContext.Exception);

            if (controller.Is())
            {
                // Model
                var model = Factory.CreateInstance<IExceptionModel>();
                model.MasterModel.ControllerName = controllerName;
                model.MasterModel.CurrentAction = action;
                model.Messages = new Messages();

                // Messages
                foreach (var message in controller.Messages)
                {
                    model.Messages.Add(message);
                }
                controller.Messages.Clear();

                var result = new ViewResult
                {
                    ViewData = new ViewDataDictionary<IViewModel>(model),
                    ViewName = View,
                    MasterName = Const.MasterPage.Names.Detail,
                };
                filterContext.Result = result;
            }
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
        }
    }
}